package com.cloud.wms.ui.group.presenter;


import android.text.TextUtils;

import com.cloud.core.base.BaseRxPresenter;
import com.cloud.core.http.error.ApiException;
import com.cloud.core.utils.MessageCreator;
import com.cloud.core.utils.TimeUtils;
import com.cloud.wms.app.FineExApplication;
import com.cloud.wms.config.HttpConfig;
import com.cloud.wms.entity.Page;
import com.cloud.wms.http.Params;
import com.cloud.wms.http.observer.LoadingObserver;
import com.cloud.wms.http.observer.ResponseWrapper;
import com.cloud.wms.tools.MemberFun;
import com.cloud.wms.tools.PageHelper;
import com.cloud.wms.tools.RxUtils;
import com.cloud.wms.tools.TaskHelper;
import com.cloud.wms.ui.group.contract.GroupObtainContract;
import com.cloud.wms.ui.group.entity.ObtainBindEntity;
import com.cloud.wms.ui.group.entity.ObtainScanContainerEntity;
import com.cloud.wms.ui.main.entity.CommodityEntity;
import com.cloud.wms.ui.main.entity.RemoteEntity;
import com.cloud.wms.ui.main.entity.TaskEntity;
import com.cloud.wms.ui.main.entity.TitleEntity;
import com.cloud.wms.ui.main.entity.UserEntity;
import com.cloud.wms.ui.sort.entity.BatchInfoEntity;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;

/**
 * @Author:Chen
 * @Date: 2021-01-14 15:51
 * @Description: 领用任务
 */
public class GroupObtainPresenter extends BaseRxPresenter<GroupObtainContract.View> implements GroupObtainContract.Presenter {
    public static final int BATCH_LIST = 0x100;

    public static final int BATCH_DETAIL = 0x101;

    public static final int SUBMIT_OBTAIN = 0x102;

    public static final int CHECK_LINE = 0x103;

    public static final int CHECK_OPERATOR = 0x104;

    public static final int BIND_INFO = 0x105;

    public static final int CONTAINER_MSG = 0x106;

    public static final int TASK = 0x108;

    @Inject
    public GroupObtainPresenter() {

    }

    /**
     * 加载团购领用波次列表
     *
     * @param batchCode
     */
    @Override
    public void loadBatchList(String batchCode, int page) {
        Params params = Params.newInstance(Params.Type.MEMBER);
        params.put("BatchTypeID", 6);//1.散单分拣，2.单sku分拣，3.笼车分拣，4.团购分拣  5、团购集货 6、团购领用 7、团购抽检
        if (!TextUtils.isEmpty(batchCode)) {
            params.put("BatchCode", batchCode);
        }
        params.put("Sorting", "createDate");
        params.put("SkipCount", PageHelper.skipCount(page));
        params.put("MaxResultCount", PageHelper.PAGE_SIZE);
        FineExApplication
                .component()
                .http()
                .sortBatchList(params)
                .map(new ResponseWrapper<>())
                .map(Page::getItems)
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<ArrayList<BatchInfoEntity>>(mView.provideContext()) {
                    @Override
                    public void onSuccess(ArrayList<BatchInfoEntity> info) {
                        if (page == 0) {
                            mView.onSuccess(MessageCreator.createMessage(info, PageHelper.LIST_NEW_DATA));
                        } else {
                            mView.onSuccess(MessageCreator.createMessage(info, PageHelper.LIST_NEXT_DATA));
                        }
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                    }
                });
    }

    /**
     * 检测波次是否生成任务并领用
     *
     * @param billId
     * @param taskCode
     */
    @Override
    public void receiveTask(long billId, String taskCode) {
        TaskHelper.receiveTask(billId + "", taskCode)
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<TaskEntity>(mView.provideContext()) {
                    @Override
                    public void onSuccess(TaskEntity info) {
                        mView.onSuccess(MessageCreator.createMessage(info, TASK));
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                    }
                });
    }

    /**
     * 获取该波次绑定的容器和集货地信息
     *
     * @param billID
     */
    @Override
    public void getBatchContainerMsg(long billID) {
        Params params = Params.newInstance(Params.Type.WAREHOUSE);
        params.put("BatchID", billID);
        FineExApplication
                .component()
                .http()
                .getBatchContainerMsg(params)
                .map(new ResponseWrapper<>())
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<ObtainScanContainerEntity>(mView.provideContext()) {
                    @Override
                    public void onSuccess(ObtainScanContainerEntity info) {
                        mView.onSuccess(MessageCreator.createMessage(info, CONTAINER_MSG));
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                    }
                });
    }

    /**
     * 加载波次商品数据
     *
     * @param billId
     */
    @Override
    public void loadBatchCommodity(long billId) {
        Params params = Params.newInstance(Params.Type.MEMBER);
        params.put("BatchTypeID", 1);//1:波次 2:订单
        params.put("DetailbillID", billId);
        FineExApplication
                .component()
                .http()
                .sortBatchDetail(params)
                .map(new ResponseWrapper<>())
                .map(batchCommodityEntity -> batchCommodityEntity.getBatchCommodity())
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<ArrayList<CommodityEntity>>(mView.provideContext()) {
                    @Override
                    public void onSuccess(ArrayList<CommodityEntity> info) {
                        mView.onSuccess(MessageCreator.createMessage(info, BATCH_DETAIL));
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                    }
                });
    }

    /**
     * 加载已绑定流水线和工号信息
     */
    @Override
    public void loadBindInfo() {
        Params params = Params.newInstance(Params.Type.MEMBER);
        params.put("EmployeesID", FineExApplication.component().loginCache().getUserInfo().getUserID());
        FineExApplication
                .component()
                .http()
                .groupObtainBindInfo(params)
                .map(new ResponseWrapper<>())
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<ObtainBindEntity>(mView.provideContext()) {
                    @Override
                    public void onSuccess(ObtainBindEntity info) {
                        mView.onSuccess(MessageCreator.createMessage(info, BIND_INFO));
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                        mView.showError();
                    }
                });
    }

    /**
     * 检验流水线
     *
     * @param lineCode
     */
    @Override
    public void checkLineCode(String lineCode) {
        Params params = Params.newInstance(Params.Type.MEMBER);
        params.put("AssemblylineNo", lineCode);
        FineExApplication
                .component()
                .http()
                .groupObtainCheckLine(params)
                .map(new ResponseWrapper<>())
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<ObtainBindEntity>(mView.provideContext()) {
                    @Override
                    public void onSuccess(ObtainBindEntity lineEntity) {
                        mView.onSuccess(MessageCreator.createMessage(lineEntity, CHECK_LINE));
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                    }
                });
    }

    /**
     * 检验操作人
     *
     * @param data
     * @param jobNumber
     */
    @Override
    public void checkOperator(List<String> data, String jobNumber) {
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).equalsIgnoreCase(jobNumber)) {
                mView.error("已添加，请勿重复扫描添加！");
                return;
            }
        }
        Params params = Params.newInstance(Params.Type.MEMBER);
        params.put("EmployeesNo", jobNumber);
        FineExApplication
                .component()
                .http()
                .groupObtainCheckOperator(params)
                .map(new ResponseWrapper<>())
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<ObtainBindEntity>(mView.provideContext()) {
                    @Override
                    public void onSuccess(ObtainBindEntity info) {
                        info.setEmployeeCode(jobNumber);
                        mView.onSuccess(MessageCreator.createMessage(info, CHECK_OPERATOR));
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                    }
                });
    }

    /**
     * 确认绑定流水线
     *
     * @param taskEntity
     * @param billId
     * @param assemblylineID
     * @param employeesID
     */
    @Override
    public void confirmObtain(TaskEntity taskEntity, long billId, String assemblylineID, List<String> employeesID, List<String> employeesNo) {
        UserEntity userEntity = FineExApplication.component().loginCache().getUserInfo();
        boolean isContain = false;//是否包含自身，当前登录用户
        for (int i = 0; i < employeesID.size(); i++) {
            if (String.valueOf(userEntity.getUserID()).equals(employeesID.get(i))) {
                isContain = true;
                break;
            }
        }
        if (!isContain) {
            employeesID.add(String.valueOf(userEntity.getUserID()));
            employeesNo.add(userEntity.getLoginNO());
        }
        Params params = Params.newInstance(Params.Type.MEMBER);
        params.put("businessID", billId);
        params.put("assemblylineID", assemblylineID);
        params.put("userID", FineExApplication.component().loginCache().getUserInfo().getUserID());
        params.put("employeesID", employeesID);
        params.put("employeesNo", employeesNo);
        if (taskEntity != null) {
            params.put("businessID", taskEntity.getBillID());
            params.put("workID", taskEntity.getWorkID());
            params.put("beginTime", taskEntity.getBeginTime());
            params.put("completeTime", TimeUtils.getCurrentDateAndTime());
            params.put("productCategory", userEntity.getProductCategory());
            params.put("jobStationID", userEntity.getJobStationID());
            params.put("appKey", taskEntity.getAppKey());
        }
        Observable<Object> observable;
        if (taskEntity != null) {
            observable = FineExApplication
                    .component()
                    .http()
                    .groupTaskObtainBatch(params)
                    .map(new ResponseWrapper<>());
        } else {
            observable = FineExApplication
                    .component()
                    .http()
                    .groupObtainBatch(params)
                    .map(new ResponseWrapper<>());
        }

        observable
                .compose(mView.toLifecycle())
                .compose(RxUtils.threadSwitch())
                .subscribe(new LoadingObserver<Object>(mView.provideContext()) {
                    @Override
                    public void onSuccess(Object info) {
                        mView.onSuccess(MessageCreator.createMessage(info, SUBMIT_OBTAIN));
                    }

                    @Override
                    public void onError(String msg) {
                        mView.error(msg);
                    }
                });
    }
}
